<?php

namespace App\Http\Controllers\Admin\Shop;

use App\Dao\UsersDao;
use App\Http\Controllers\Admin\BaseAdminController;
use App\Models\CollectionShops;
use App\Models\Shopcomment;
use App\Models\ShopRule;
use App\Models\Shops;
use App\Models\Goods;
use App\Models\UploadedFile;
use App\Models\Users;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Str;

/**
 * 店铺控制器
 *
 * @author lxp
 * @package App\Http\Controllers\Shops
 */
class ShopsController extends BaseAdminController
{

    public function __construct()
    {
        parent::__construct();
    }

    /**
     * 商家列表
     *
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     * @author yh 20200318
     */
    public function refundShop(){
        // 处理排序
        $sort = request('sort', 'id');
        $order = request('order', 'desc');

        $query = Shops::orderBy($sort, $order);
        $query->where('status',0);
        if (request('title')) {
            if (request('title')) {
                $query->where('title', 'LIKE', "%" . request('title') . "%");
            } elseif (is_mobile(request('title'))) {
                $query->where('phone', request('title'));
            } else {
                $query->where('username', 'LIKE', "%" . request('title') . "%");
            }
        }
        // 筛选注册时间
        if (request('created_at')) {
            list($begin, $end) = explode(' - ', request('created_at'));
            $query->whereBetween('created_at', [
                date('Y-m-d H:i:s', strtotime($begin)),
                date('Y-m-d H:i:s', strtotime('+1 day', strtotime($end)))
            ]);
        }
        // 取得列表
        $shops = $query->select([
            'id',
            'avatar',
            'zhizhao',
            'title',
            'des',
            'username',
            'phone',
            'status',
            'star',
            'num',
            'created_at',
            'is_recommend'
        ])->paginate(parent::PERPAGE);
        // 将查询参数拼接到分页链接中
        $shops->appends(app('request')->all());

        return view('admin.shop.refundShops', [
            'shops' => $shops,
        ]);
    }

    public function index()
    {
        // 处理排序
        $sort = request('sort', 'id');
        $order = request('order', 'desc');

        $query = Shops::orderBy('rank','desc')->orderBy($sort, $order);
        $query->where('status', '!=' , 0);
        if (request('title')) {
            if (request('title')) {
                $query->where('title', 'LIKE', "%" . request('title') . "%");
            } elseif (is_mobile(request('title'))) {
                $query->where('phone', request('title'));
            } else {
                $query->where('username', 'LIKE', "%" . request('title') . "%");
            }
        }
        // 筛选注册时间
        if (request('created_at')) {
            list($begin, $end) = explode(' - ', request('created_at'));
            $query->whereBetween('created_at', [
                date('Y-m-d H:i:s', strtotime($begin)),
                date('Y-m-d H:i:s', strtotime('+1 day', strtotime($end)))
            ]);
        }
        // 取得列表
        $shops = $query->select([
            'id',
            'avatar',
            'zhizhao',
            'title',
            'des',
            'username',
            'phone',
            'status',
            'rank',
            'star',
            'num',
            'created_at',
            'is_recommend',
            'show_phone'
        ])->paginate(parent::PERPAGE);
        // 将查询参数拼接到分页链接中
        $shops->appends(app('request')->all());

        return view('admin.shop.shops', [
            'shops' => $shops,
        ]);
    }

    /**
     * 添加店铺
     *
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     * @author lxp 20170825
     */
    public function add()
    {
        return view('admin.shop.shops_form');
    }

    /**
     * 编辑用户
     *
     * @param $uid
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     * @author lxp 20170111
     */
    public function edit($id)
    {
        // 取得用户信息
        $user = Shops::findOrFail($id);

        return view('admin.shop.shops_form', [
            'user' => $user
        ]);
    }

    /**
     * 审核店铺
     *
     * @param $uid
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     * @author yh 20170111
     */
    public function shen($id)
    {
        // 取得用户信息
        $user = Shops::findOrFail($id);

        return view('admin.shop.shops_shen', [
            'user' => $user
        ]);
    }
    /**
     * 店家评论管理 comment
     * @author  yh 20200401
     */
    public function comment($id){
        // 取得评论列表
        $sort = request('sort', 'id');
        $order = request('order', 'desc');

        $query = Shopcomment::orderBy($sort, $order);
        if (request('title')) {
            if (request('title')) {
                $query->where('title', 'LIKE', "%" . request('title') . "%");
            } else {
                $query->where('nickname', 'LIKE', "%" . request('title') . "%");
            }
        }
        // 发布时间时间
        if (request('created_at')) {
            list($begin, $end) = explode(' - ', request('created_at'));
            $query->whereBetween('created_at', [
                date('Y-m-d H:i:s', strtotime($begin)),
                date('Y-m-d H:i:s', strtotime('+1 day', strtotime($end)))
            ]);
        }

        $id= request('id');
        // 取得列表
        $query->where('shop_id',$id);
        $forums = $query->select([
            'id',
            'uname',
            'comment',
            'uid',
            'imgs',
            'status',
            'created_at'
        ])->paginate(parent::PERPAGE);
        // 将查询参数拼接到分页链接中
        $forums->appends(app('request')->all());

        return view('admin.shop.comments', [
            'forums' => $forums,
            'id'=>$id,
        ]);
    }
    public function comment_add($id)
    {
        // 取得用户信息
        $user = Shops::findOrFail($id);

        return view('admin.shop.comments_form', [
            'forums' => $user,
            'id'=>$id
        ]);
    }
    public function comment_save()
    {
        // 取得用户信息
        $id = request('id');
        $user = Shopcomment::findOrNew($id);
        $user->uid = Auth::user()->uid;
        $uinfo = Users::where('uid', Auth::user()->uid)->select('uid', 'nickname', 'avatar')->first();
//        $user->avatar =get_file_url($uinfo ->avatar);
        $user->uname =$uinfo ->nickname;
        $user->imgs =request('imgs');
        $user->comment = request('comment');
        $user->shop_id = request('shop_id');
        $user->status = 0;
        $user->save();
//        Shops::where('id',request('shop_id'))->increment('comment_num');
        return $this->success(get_session_url('index'));
    }
    /**
     * 厂家申请入驻规则
     * @author  yh 20200401
     */
    public function saveRule()
    {
        $content = request('content');
        $rule = ShopRule::findOrNew(request('id'));
        $rule->content = $content;
        $rule->uid = Auth::user()->uid;
        $rule->save();
        return $this->success();
    }
    /**
     * 删除用户
     *
     * @author lxp 20160713
     * @param int $uid
     * @return \Illuminate\Http\JsonResponse
     */
    public function comment_delete($id)
    {
        if (request()->ajax() && intval($id)) {
            // 判断用户是否可以被删除
            // 删除用户
            Shopcomment::destroy($id);
            return $this->success();
        }
    }
    /**
     * 审核评论
     *
     * @author yh 20170111
     * @param $uid
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function comment_shen($id)
    {
        // 取得用户信息
        $user = Shopcomment::findOrFail($id);
        $users = Shops::findOrFail($user->shop_id);
        return view('admin.shop.comments_shen', [
            'user' => $user,
            'users' =>$users
        ]);
    }
    /**
     * 评论审核
     *
     * @author yh 20200322
     * @param int $uid
     * @return \Illuminate\Http\JsonResponse
     */
    public function comment_refund()
    {
        $user = Shopcomment::findOrNew(request('id'));
        $user -> status =intval(request('status'));
        $rule = [];
        if(request('status')==0){
            $rule = array_merge([
                'refund_msg' => 'required'
            ], $rule);
            $this->validate(request(), $rule, [], [
                'refund_msg'=>'审核不通过原因',
            ]);
        }
        $user -> refund_msg = request('refund_msg');
        $user->save();
        return $this->success(get_session_url('index'));
    }
    /**
     * 修改店铺排名
     *
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     * @author lxp 20170206
     */
    public function rank(){
        $id = request('id');
        $rank = request('rank');
        $shops = Shops::where('rank',$rank)->first();

        $shop2 = Shops::where('id',$id)->first();
        if($shops){

            $shops->rank= $shop2->rank;
            $shop2->rank = $rank;
            $shops->save();
        }else{
            $shop2->rank = $rank;
        }
        $shop2->save();
        return response_json(1,'','success');

    }
    public function shopRule()
    {

        $rule = ShopRule::where('id', 1)->first();
        return view('admin.shop.shops_rule', [
            'rule' => $rule
        ]);
    }

    /**
     * 保存店铺
     *
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     * @author lxp 20170206
     */
    public function save()
    {

        // 保存用户信息
        DB::transaction(function () {
            $rule = [
                'phone' => 'required|mobile|unique:shops,phone,' . request('id') . ',id',
                'username' => 'required|unique:shops,username,' . request('id') . ',id'
            ];
            if (!request('id')) {
                $rule = array_merge([
                    'title' => 'required|unique:shops,title,' . request('id') . ',id',

                    'avatar' => 'required|'
                ], $rule);
            }

            $this->validate(request(), $rule, [], [

                'avatar' => '店铺图片',
                'username' => '店主姓名',
                'title' => '店名',

            ]);

            $user = Shops::findOrNew(request('id'));
            $user->avatar = get_file_url(request('avatar'));
            $user->title = request('title');
            $user->username = request('username');
            $user->phone = request('phone');
            $user->des = request('des');
            // 生成密码盐
            $salt = Str::random(6);
            if (request('id') == 0) {
                $users = new Users();
                $users->username = request('username');
                $users->password = get_password(request('password'), $salt);
                $users->phone = request('phone');
                $users->nickname = UsersDao::get_nickname();
                $users->salt = $salt;
                $users->lastloginip = client_real_ip();
                $users->plat = request('p');
                $users->address_id = 0;
                $users->status = 1;
                $users->allow_comment = 1;
                $users->save();
                if (!$users->uid) {
                    return response_json(0, '', '用户已经存在');
                }
            } else {
                $users = Users::where('phone', request('phone'))->first();
                $users->phone = request('phone');
                $users->password = get_password(request('password'), $salt);
                $users->save();
            }

            $user->is_recommend = 2;
            if (request('zhizhao') == '') {
                $user->is_vip = 0;
            } else {
                $user->is_vip = 1;
            }

            $user->uid = $users->uid;
            $user->status = 0;
            $user->zhizhao = get_file_url(request('zhizhao'));
            $user->save();
            // 更新附件id
            if (!request('id')) {
                // 更新店铺图片
                if (intval(request('shop_file_id'))) {
                    UploadedFile::where('file_id', intval(request('shop_file_id')))->update(['item_id' => $user->id]);
                }
                //更新执照
                if (intval(request('zhizhao_file_id'))) {
                    UploadedFile::where('file_id', intval(request('zhizhao_file_id')))->update(['item_id' => $user->id]);
                }
            }
        });

        return $this->success(get_session_url('index'));
    }

    /**
     * 删除商家
     *
     * @param int $uid
     * @return \Illuminate\Http\JsonResponse
     * @author lxp 20160713
     */
    public function delete($id)
    {
        if (request()->ajax() && intval($id)) {
            // 判断用户是否可以被删除
            // 删除用户
            Shops::destroy($id);
            Goods::where('shop_id',$id)->delete();
            CollectionShops::where('shop_id',$id)->delete();
            return $this->success();
        }
    }
    /**
     * 商家关闭和显示
     *  @api changeShop
     * @apiParams id
     * @return \Illuminate\Http\JsonResponse
     * @author yh 20200406
     *
     **/
    public function changeShop($id){
        $shop = Shops::where('id',$id)->first();
        $status = $shop->status;
        if($status==2){
            $shop->status=1;
            Goods::where('shop_id',$id)->update(['status'=>1]);
        }else{
            $shop->status=2;
            Goods::where('shop_id',$id)->update(['status'=>0]);
        }
        $shop->save();
        return $this->success();
    }
    /**
     * 商家是否显示联系方式
     *  @api showPhone
     * @apiParams id
     * @return \Illuminate\Http\JsonResponse
     * @author yh 20200406
     *
     **/
    public function showPhone($id){
        $shop = Shops::where('id',$id)->first();
        $show_phone = $shop->show_phone;
        if( $show_phone==0){
            $shop->show_phone=1;

        }else{
            $shop->show_phone=0;
        }
        $shop->save();
        return $this->success();
    }
    /**
     * 商家推荐首页
     *  @api changeShop
     * @apiParams id
     * @return \Illuminate\Http\JsonResponse
     * @author yh 20200406
     *
     **/
    public function recommend($id){
        $shop = Shops::where('id',$id)->first();
        $status = $shop->is_recommend;
        if($status==2){
            $shop->is_recommend=1;
            $shop->status=1;
        }else{
            $shop->is_recommend=2;
        }
        $shop->save();
        return $this->success();
    }


    /**
     * 审核店铺
     *
     * @param int $uid
     * @return \Illuminate\Http\JsonResponse
     * @author yh 20200322
     */
    public function refund()
    {
        $user = Shops::findOrNew(request('id'));
        $user->status = intval(request('status'));
        $rule = [];
        if (request('status') == 2) {
            $rule = array_merge([
                'refund_msg' => 'required'
            ], $rule);
            $this->validate(request(), $rule, [], [
                'refund_msg' => '审核不通过原因',
            ]);
        }
        $user->refund_msg = request('refund_msg');
        if ($user->zhizhao != '') {
            $user->is_vip = 1;
        }
        $user->save();
        return $this->success(get_session_url('index'));
    }
}